package com.tlgen.tomcat.handler;

import com.alibaba.fastjson.JSONObject;
import com.tlgen.tomcat.model.HttpRequestResponse;
import com.tlgen.tomcat.model.RequestMethodAndUrl;
import com.tlgen.tomcat.model.Response;
import com.tlgen.tomcat.constant.Constants;
import com.tlgen.tomcat.utils.CheckRequestUtils;
import com.tlgen.tomcat.utils.ReflectionUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Objects;

import static com.tlgen.tomcat.utils.SocketParserUtils.createRequestResponse;

public class RequestTask implements Runnable {

    private Socket socket = null;

    public RequestTask(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (InputStream inputStream = socket.getInputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                String dataReceived = new String(buffer, 0, bytesRead);

                OutputStream outputStream = null;
                PrintWriter writer = null;
                outputStream = socket.getOutputStream();
                writer = new PrintWriter(outputStream);

                HttpRequestResponse requestResponse = createRequestResponse(dataReceived);
                Response response = requestResponse.getResponse();
                RequestMethodAndUrl requestMethodAndUrl = CheckRequestUtils.checkRequestPathAndRequestType(socket, inputStream, dataReceived);
                // 调用指定方法
                if (Objects.nonNull(requestMethodAndUrl)) {
                    Object result = ReflectionUtils.invokeHttpRequest(requestMethodAndUrl);
                    System.out.println("调用结果");
                    System.out.println(result);
                    response.setData(Constants.RESPONSE_APPLICATION_JSON_HEADER + JSONObject.toJSONString(result));
                } else {
                    response.setData(Constants.RESPONSE_APPLICATION_JSON_HEADER);
                }
                // 添加自定义拦截器
                ReflectionUtils.doResponseFilter(requestResponse.getRequest(), response);

                writer.write(response.getData());
                writer.flush(); // 提交输出数据, 浏览器才可以收到返回的数据

                break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭socket连接
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
